﻿// HisDataManager.cpp : 实现文件
//

#include "stdafx.h"
#include "BtsClient.h"
#include "HisDataManager.h"
#include "afxdialogex.h"
#include "SettingMgr.h"
#include "File/FileNda1.h"
#include "CommHandler.h"

// CHisDataManager 对话框

IMPLEMENT_DYNAMIC(CHisDataManager, CDialogEx)

CHisDataManager::CHisDataManager(CWnd* pParent /*=NULL*/)
	: CDialogEx(CHisDataManager::IDD, pParent)
	, m_nDevID(0)
	, m_nChlNo(0)
	, m_nTimeStyle(0)
	, m_nDays(0)
	, m_sDateFrom(_T(""))
	, m_sDateTo(_T(""))
	, m_nAutpDelDays(0)
	, m_TimeF(0)
	, m_TimeT(0)
	, m_strBarcode(_T(""))
{

}

CHisDataManager::~CHisDataManager()
{
}

void CHisDataManager::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_DATA_LIST, m_FileList);
	DDX_Text(pDX, IDC_EDIT_DevID, m_nDevID);
	DDX_Text(pDX, IDC_EDIT_ChlNo, m_nChlNo);
	DDX_Radio(pDX, IDC_RADIO_NULL, m_nTimeStyle);
	DDX_Text(pDX, IDC_EDIT_LAST_DAYS, m_nDays);
	DDV_MinMaxInt(pDX, m_nDays, 0, 999999);
	DDX_Text(pDX, IDC_EDIT_DAYS, m_nAutpDelDays);
	DDX_DateTimeCtrl(pDX, IDC_DATE_FROM, m_TimeF);
	DDX_DateTimeCtrl(pDX, IDC_DATE_TO, m_TimeT);
	DDX_Text(pDX, IDC_EDIT4, m_strBarcode);
}


BEGIN_MESSAGE_MAP(CHisDataManager, CDialogEx)
	ON_BN_CLICKED(IDC_SEARCH, &CHisDataManager::OnBnClickedSearch)
	ON_BN_CLICKED(IDC_RADIO_NULL, &CHisDataManager::OnBnClickedRadioNull)
	ON_BN_CLICKED(IDC_RADIO_LAST, &CHisDataManager::OnBnClickedRadioLast)
	ON_BN_CLICKED(IDC_RADIO_FROM_DATE, &CHisDataManager::OnBnClickedRadioFromDate)
	ON_BN_CLICKED(IDC_CHECKALL, &CHisDataManager::OnBnClickedCheckall)
	ON_NOTIFY(NM_DBLCLK, IDC_DATA_LIST, &CHisDataManager::OnNMDblclkDataList)
	ON_BN_CLICKED(IDC_DELLETE, &CHisDataManager::OnBnClickedDellete)
	ON_BN_CLICKED(IDOK, &CHisDataManager::OnBnClickedOk)
END_MESSAGE_MAP()


// CHisDataManager 消息处理程序


BOOL CHisDataManager::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	GetDlgItem(IDC_EDIT_LAST_DAYS)->EnableWindow(FALSE);
	GetDlgItem(IDC_DATE_FROM)->EnableWindow(FALSE);
	GetDlgItem(IDC_DATE_TO)->EnableWindow(FALSE);
	m_FileList.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT|LVS_EX_CHECKBOXES);
	m_FileList.InsertColumn(0,_T("选择"),LVCFMT_CENTER,50);//添加列标题 
	m_FileList.InsertColumn(1,_T("设备-通道-批次"),LVCFMT_LEFT,70);
	m_FileList.InsertColumn(2,_T("启动时间"),LVCFMT_LEFT,130); 
	m_FileList.InsertColumn(3,_T("条码"),LVCFMT_LEFT,100); 
	m_FileList.InsertColumn(4,_T("状态"),LVCFMT_LEFT,60); 
	// TODO:  在此添加额外的初始化
	m_TimeF = m_TimeT = CTime::GetCurrentTime();
	m_nAutpDelDays = atoi(g_Setting->GetUserFileKeyValue("HisDataManager", "Days").c_str());
	UpdateData(FALSE);
	CenterWindow();
	string sHisPath = g_Setting->GetUserFileKeyValue("DevList", "at_data_path");
	if (sHisPath.empty())
	{
		sHisPath = g_Setting->GetSysPath() + "BDF_Data\\";
		_mkdir(sHisPath.c_str());
	}
	m_strFold = CA2W(sHisPath.c_str());
	return TRUE;  // return TRUE unless you set the focus to a control
	// 异常: OCX 属性页应返回 FALSE
}


void CHisDataManager::OnBnClickedSearch()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	m_FileList.DeleteAllItems();
	m_FilePath.RemoveAll();
	CString DateFrom,DateTo;
	if(m_nTimeStyle == 2)
	{
		DateFrom = m_TimeF.Format(_T("%Y%m%d"));
		DateTo = m_TimeT.Format(_T("%Y%m%d"));
		if(StrCmp(DateFrom,DateTo)>0)
		{
			AfxMessageBox(_T("起始日期不能大于截至日期！"));
			return;
		}
	}
	else if (m_nTimeStyle == 1)
	{
		CTime Time;
		Time = CTime::GetCurrentTime();
		DateTo = Time.Format(_T("%Y%m%d"));
		Time -= CTimeSpan(m_nDays, 0, 0, 0 );
		DateFrom = Time.Format(_T("%Y%m%d"));
	}
	CString condition;
	CString DevChl;
	DevChl.Format(_T("\\*_%d_%d_*"),m_nDevID,m_nChlNo);
	DevChl.Replace(_T('0'),_T('*'));
	m_strBarcode.Trim();
	if (!m_strBarcode.IsEmpty())
	{
		DevChl.Format(_T("%s_%s_*"),DevChl,m_strBarcode);
	}
	CFileFind fileFind;
	CFileFind Finder;
	BOOL IsFinded = fileFind.FindFile(m_strFold+_T('*'));
	CString spath;
	int index = 0;
	char NUM[30] = {0};
	while(IsFinded)
	{
		IsFinded = fileFind.FindNextFile();
		if(fileFind.IsDirectory())
		{
			CString strDirName = fileFind.GetFileName();
			if(strDirName=="." || strDirName=="..")
				continue;
			spath = fileFind.GetFilePath();
			if(PathIsDirectoryEmpty(spath))
				RemoveDirectory(spath);
			if(m_nTimeStyle != 0 && (StrCmp(DateFrom,strDirName)>0 || StrCmp(strDirName,DateTo)>0))
			{
				continue;
			}
			spath += DevChl;
			BOOL Finded = Finder.FindFile(spath);
			CString lastFileName;
			const string SEP = "_";
			while(Finded)
			{
				Finded = Finder.FindNextFile();
				CString fileName = Finder.GetFileName();//Finder.GetLength();
			
				string sFileName = CW2A(fileName);
				vector<string> vInfo = explode(SEP, sFileName);
				if (vInfo.size() < 5)
					continue; 
				string sFileFront = vInfo[0] + SEP +vInfo[1] + SEP +vInfo[2] + SEP +vInfo[3];
				if(lastFileName == CA2W(sFileFront.c_str()))
					continue;
				string sDateTime = vInfo[0].substr(0,4);
				sDateTime += "/";
				sDateTime += vInfo[0].substr(4,2);
				sDateTime += "/";
				sDateTime += vInfo[0].substr(6,2);
				sDateTime += " ";
				sDateTime += vInfo[0].substr(9,2);
				sDateTime += ":";
				sDateTime += vInfo[0].substr(11,2);
				sDateTime += ":";
				sDateTime += vInfo[0].substr(13,2);

				string sDevChlBatch = vInfo[1] + "-" + vInfo[2] + "-" + vInfo[3];
				int nlen = vInfo[4].length();
				itoa(1+index,NUM,10);
				m_FileList.InsertItem(index,CA2W(NUM));
				m_FileList.SetItemText(index,2, CA2W(sDateTime.c_str()));

				m_FileList.SetItemText(index,1, CA2W(sDevChlBatch.c_str()));
				if (vInfo[4].length() > 2 && vInfo.size() > 5)
				{
					m_FileList.SetItemText(index,3, CA2W(vInfo[4].c_str()));
					sFileFront += SEP +vInfo[4];
				} 
				if(6 == nlen)
					m_FileList.SetItemText(index,4,_T("完成文件"));
				else if(10 == nlen)
				{
					sDateTime = "中间文件(";
					sDateTime += vInfo[4].substr(2,2);
					sDateTime += ':';
					sDateTime += vInfo[4].substr(4,2);
					sDateTime += ')';
					m_FileList.SetItemText(index,4,CA2W(sDateTime.c_str()));
				}
				else
					m_FileList.SetItemText(index,4,_T("缓存文件"));
				lastFileName = CA2W(sFileFront.c_str());
				m_FilePath.Add(m_strFold + strDirName + '\\' + lastFileName);
				index++;
			}
			Finder.Close();
		}
	}
	fileFind.Close();
}


void CHisDataManager::OnBnClickedRadioNull()
{
	// TODO: 在此添加控件通知处理程序代码
	GetDlgItem(IDC_EDIT_LAST_DAYS)->EnableWindow(FALSE);
	GetDlgItem(IDC_DATE_FROM)->EnableWindow(FALSE);
	GetDlgItem(IDC_DATE_TO)->EnableWindow(FALSE);
	//UpdateData(FALSE);
}


void CHisDataManager::OnBnClickedRadioLast()
{
	// TODO: 在此添加控件通知处理程序代码
	GetDlgItem(IDC_EDIT_LAST_DAYS)->EnableWindow(TRUE);
	GetDlgItem(IDC_DATE_FROM)->EnableWindow(FALSE);
	GetDlgItem(IDC_DATE_TO)->EnableWindow(FALSE);
	//UpdateData(FALSE);
}


void CHisDataManager::OnBnClickedRadioFromDate()
{
	// TODO: 在此添加控件通知处理程序代码
	GetDlgItem(IDC_EDIT_LAST_DAYS)->EnableWindow(FALSE);
	GetDlgItem(IDC_DATE_FROM)->EnableWindow(TRUE);
	GetDlgItem(IDC_DATE_TO)->EnableWindow(TRUE);
	//UpdateData(FALSE);
}


void CHisDataManager::OnBnClickedCheckall()
{
	// TODO: 在此添加控件通知处理程序代码
	int fileCount = m_FileList.GetItemCount();
	int num = 0;
	BOOL bChecked = TRUE;
	for(int i = 0;i < fileCount;i++)
		if(m_FileList.GetCheck(i))
			num++;
	if(num == fileCount)
		bChecked = FALSE;
	for(int i = 0;i < fileCount;i++)
		m_FileList.SetCheck(i,bChecked);
	UpdateData(FALSE);
}


void CHisDataManager::OnNMDblclkDataList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: 在此添加控件通知处理程序代码
	int Num = pNMItemActivate->iItem;
	if(Num < 0)
		return;
	CString sCaFullName = m_FilePath.GetAt(Num) + _T("_Cache.tmp");
	CString sCacheBDF = m_FilePath.GetAt(Num) + _T("_AT_TMP_Cache");
	CString strTmpBdf = m_FilePath.GetAt(Num) + _T("_AT_TMP.bdf");//即将被打开的临时数据文件
	CString strBdf = m_FilePath.GetAt(Num) + _T("_AT.bdf");
	if (_waccess(sCaFullName, 0) != -1 && _waccess(sCacheBDF, 0) != -1)	//有缓存文件
	{
		CFileNda daFile;
		daFile.Deserialize(sCaFullName);		
		UINT64 nFrom = daFile.GetCurrPos();
		if ( _waccess(strTmpBdf, 0) != -1)	//已经有临时tmpBDF 打开
		{
			if (0 != _wremove(strTmpBdf))
			{
				AfxMessageBox(_T("请先关闭DA软件！"));
				return;
			}
		}
		BOOL bCopy = ::CopyFile(sCacheBDF, strTmpBdf, FALSE);
		if (!daFile.CreateFile(strTmpBdf.GetBuffer(MAX_PATH)))
		{
			return;
		}
		daFile.Finish();
		string sDaFile = GetSetting()->GetSysPath() + g_CommHandler.GetBtsdaPath(); //读取相对路径
		CString strExe =  CA2W(sDaFile.c_str());
		if (!strExe.IsEmpty())
		{
			strTmpBdf.Insert(0,_T("\""));
			strTmpBdf += _T("\"");
			SetCurrentDirectoryW(_T("BTSDA"));
			ShellExecute(NULL, _T("open"),strExe, strTmpBdf, NULL, SW_SHOWNORMAL);
			return;
		}
		else
		{
			AfxMessageBox(_T("未配置DA文件路径！"));
			return;
		}
	}
	else if (_waccess(strTmpBdf, 0) != -1)
	{
		string sDaFile = GetSetting()->GetSysPath() + g_CommHandler.GetBtsdaPath(); //读取相对路径
		CString strExe = CA2W(sDaFile.c_str());
		if (!strExe.IsEmpty())
		{
			strTmpBdf.Insert(0,_T("\""));
			strTmpBdf += _T("\"");
			SetCurrentDirectoryW(_T("BTSDA"));
			ShellExecute(NULL, _T("open"), strExe, strTmpBdf, NULL, SW_SHOWNORMAL);
		}
	}
	else if (_waccess(strBdf, 0) != -1)
	{
		string sDaFile = GetSetting()->GetSysPath() + g_CommHandler.GetBtsdaPath(); //读取相对路径
		CString strExe = CA2W(sDaFile.c_str());
		if (!strExe.IsEmpty())
		{
			strBdf.Insert(0,_T("\""));
			strBdf += _T("\"");
			SetCurrentDirectoryW(_T("BTSDA"));
			ShellExecute(NULL, _T("open"), strExe, strBdf, NULL, SW_SHOWNORMAL);
		}
	}
	else
	{
		AfxMessageBox(_T("缓存文件不完整，无法打开！"));
	}
	*pResult = 0;
}


void CHisDataManager::OnBnClickedDellete()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	int nCount = m_FileList.GetItemCount();
	int bSeccess = 0;
	CFileFind fileFind;
	for(int i = 0;i < nCount;i++)
	{
		if(m_FileList.GetCheck(i))
		{
			CString FilePath = m_FilePath.GetAt(i);
			BOOL IsFinded = fileFind.FindFile(FilePath + _T("*"));
			while(IsFinded)
			{
				IsFinded = fileFind.FindNextFile();
				CString filepath = fileFind.GetFilePath();
				if(bSeccess = _wremove(filepath) == 0)
					CRLog(E_DEBUG, "删除了文件%s",CW2A(FilePath));
			}
			m_FileList.DeleteItem(i);
		}
	}
}


void CHisDataManager::OnBnClickedOk()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	if(m_nAutpDelDays < 0)
	{
		AfxMessageBox(_T("请设置正确的自动清理日期！"));
		return;
	}
	char days[30] = {0};
	itoa(m_nAutpDelDays,days,10);
	g_Setting->SetUserFileKeyValue("HisDataManager", "Days",days);
	//CDialogEx::OnOK();
}

void CHisDataManager::SetCurChl( int nDevID, int nChlID )
{
	m_nDevID = nDevID;
	m_nChlNo = nChlID;
	if (this->GetSafeHwnd() && this->IsWindowVisible())
	{
		UpdateData(FALSE);
	}
}
